<template>
  <div class="system-container">
    <el-tabs v-model="activeName" type="border-card" class="system-container-w">
      <el-tab-pane name="1" label="装置设置">
        <template v-if="activeName === '1'">
          <div class="device-settings">
            <div class="device-settings-item">
              <label>装置类型：</label>
              <el-select disabled v-model="name" placeholder="">
                <el-option label="CKM2008G" value="CKM2008G" />
              </el-select>
            </div>
            <div class="device-settings-item">
              <label>装置数量：</label>
              <el-select disabled v-model="num" placeholder="">
                <el-option label="1" value="1" />
              </el-select>
            </div>
          </div>
          <div class="device-info">
            <p>
              <span class="label">基本信息：</span
              ><span>1功率源，单面16表位</span>
            </p>
            <p>
              <span class="label">挂表设置：</span><span>可挂真表或仿真表</span>
            </p>
            <p>
              <span class="label">变比：</span
              ><span>液晶显示TV，TA等基本信息</span>
            </p>
            <p>
              <span class="label">表尾错误接线：</span
              ><span>12种基本错误可选</span>
            </p>
            <p>
              <span class="label">485线错误：</span
              ><span>有(485错误板设置)</span>
            </p>
          </div>
          <!-- <div class="device-info">
            <el-button>确定</el-button>
          </div> -->
        </template>
      </el-tab-pane>
      <el-tab-pane name="2" label="通讯参数">
        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="name" label="部件名称" width="180" />
          <el-table-column prop="ip" label="Ip地址" width="180">
            <template #default="scope">
              <el-input
                v-if="scope.row.ipState"
                v-model="scope.row.ip"
                @focus="focusEvent(scope.row, scope.$index, scope.column)"
                @blur="blurEvent(scope.row, scope.$index, scope.column)"
              ></el-input>
              <p @click="cellClick(scope.row, scope.column)" v-else>
                {{ scope.row.ip }}
              </p>
            </template>
          </el-table-column>
          <el-table-column prop="port" label="端口号">
            <template #default="scope">
              <el-input
                v-if="scope.row.portState"
                v-model="scope.row.port"
                @focus="focusEvent(scope.row, scope.$index, scope.column)"
                @blur="blurEvent(scope.row, scope.$index, scope.column)"
              ></el-input>
              <p @click="cellClick(scope.row, scope.column)" v-else>
                {{ scope.row.port }}
              </p>
            </template>
          </el-table-column>
        </el-table>
        <!-- <div class="device-info">
          <el-button>确定</el-button>
        </div> -->
      </el-tab-pane>
      <el-tab-pane name="3" label="终端参数">
        <div>
          <div>
            <el-table
              highlight-current-row
              :data="terminalParameters"
              style="width: 100%"
              @row-click="rowClick"
            >
              <el-table-column prop="status" label="状态" width="180" />
              <el-table-column prop="terName" label="终端号" width="180" />
              <el-table-column prop="position" label="表位" />
              <el-table-column prop="commType" label="通讯类型" />
            </el-table>
          </div>
          <div class="terminalParam-btn">
            <el-button @click="add">新增</el-button>
            <el-button @click="del">删除</el-button>
            <el-button @click="edit">修改</el-button>
          </div>
        </div>
        <!-- <div class="device-info">
          <el-button>确定</el-button>
        </div> -->
      </el-tab-pane>
      <el-tab-pane name="4" label="修改密码">
        <div style="margin-top: 10px; display: flex; justify-content: center">
          <fieldset style="padding: 15px 15px">
            <legend>修改密码:</legend>
            <el-form
              ref="ruleFormRef"
              style="max-width: 600px"
              :model="ruleForm"
              status-icon
              :rules="rules"
              label-width="auto"
              class="demo-ruleForm"
            >
              <el-form-item
                style="margin-bottom: 20px"
                label="旧密码"
                prop="oldPass"
              >
                <el-input
                  v-model="ruleForm.oldPass"
                  type="password"
                  show-password
                  autocomplete="off"
                  @blur="checkPwd"
                />
              </el-form-item>
              <el-form-item
                style="margin-bottom: 20px"
                label="新密码"
                prop="pass"
              >
                <el-input
                  v-model="ruleForm.pass"
                  type="password"
                  show-password
                  autocomplete="off"
                />
              </el-form-item>
              <el-form-item style="margin-left: 65px">
                <el-button type="primary" @click="submitForm(ruleFormRef)"
                  >确认</el-button
                >
                <el-button @click="resetForm(ruleFormRef)">取消</el-button>
              </el-form-item>
            </el-form>
          </fieldset>
          <fieldset style="margin-left: 15px; padding: 15px 15px">
            <legend>密码权限:</legend>
            <el-form
              style="margin-top: 35px"
              :model="ruleForm"
              status-icon
              label-width="auto"
              class="demo-ruleForm"
            >
              <el-form-item
                style="margin-bottom: 20px"
                label="是否输入密码"
                prop="state"
              >
                <el-switch @change="setPwdStatue" v-model="ruleForm.state" />
              </el-form-item>
            </el-form>
          </fieldset>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- 新增弹窗 -->
    <TerminalParametersRef
      @is-show="isShow"
      :type="type"
      :terminalParamVisible="terminalParamVisible"
      @doTerminalParameters="doTerminalParameters"
      :position="position"
    ></TerminalParametersRef>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import TerminalParametersRef from "@/components/dialog/terminalParameters.vue";
import {
  terminalList,
  terminalRemove,
  terminalSave,
  terminalUpdate,
  devList,
  devUpdate,
  userCheckPassword,
  userUpdatePassword,
  userUpdateState,
  userSelectState,
} from "@/api/source.js";

const name = ref("CKM2008G");
const num = ref("1");
const activeName = ref("1");
const tableData = ref([
  {
    label: "装置表位",
    ip: "192.168.0.158",
    port: "80",
  },
  {
    label: "POWER",
    ip: "192.168.0.158",
    port: "80",
  },
]);
const terminalParameters = ref([
  {
    status: 0,
    port: "192.168.0.158",
    epitope: "80",
    communicationType: "",
  },
]);
const terminalParamVisible = ref(false);
const currentData = ref();
const type = ref("1");
const posArr = ref([]);
const position = ref("");
const ruleForm = reactive({
  pass: "",
  oldPass: "",
  state: false,
  // checkPass: "",
});
const ruleFormRef = ref();
const validatePass = async (rule, value, callback) => {
  console.log(rule, value);
  if (value === "") {
    callback(new Error("请输入旧密码"));
  } else {
    if (ruleForm.oldPass !== "") {
      if (!ruleFormRef.value) return;
      let parm = {
        password: ruleForm.oldPass,
      };
      let res = await userCheckPassword(parm);
      if (!res.data) {
        callback(new Error("密码不正确"));
      }
    }
    return callback();
  }
};
const rules = reactive({
  pass: [{ required: true, message: "请输入密码", trigger: "blur" }],
  oldPass: [{ required: true, validator: validatePass, trigger: "blur" }],
});

onMounted(() => {
  init();
  getDevList();
  isPassword();
});
const init = async () => {
  posArr.value = [];
  await terminalList()
    .then((res) => {
      terminalParameters.value = res.data;
      terminalParameters.value.forEach((item) => {
        posArr.value.push(item.position);
      });
      // console.log(res);
    })
    .catch((err) => {
      console.log(err);
    });
};
const getDevList = async () => {
  await devList()
    .then((res) => {
      tableData.value = res.data;
      // console.log(res);
    })
    .catch((err) => {
      console.log(err);
    });
};
//新增
const add = () => {
  type.value = "1";
  position.value = "";
  terminalParamVisible.value = true;
};
//删除
const del = async () => {
  if (currentData.value) {
    let parm = {
      id: currentData.value.terId,
    };
    await terminalRemove(parm)
      .then((res) => {
        init();
        ElMessage({
          message: "删除成功",
          type: "success",
        });
        // console.log(res);
      })
      .catch((err) => {
        console.log(err);
        ElMessage({
          message: "删除失败",
          type: "warning",
        });
      });
  } else {
    ElMessage({
      message: "请选择数据",
      type: "warning",
    });
  }
};
const doTerminalParameters = async (parm) => {
  // console.log(parm);
  parm.cldList.forEach((item) => {
    delete item.id;
    delete item.ids;
  });
  parm.terName = "终端";
  let msg = "新增";
  if (posArr.value.includes(Number(parm.position))) {
    ElMessage({
      message: msg + "一个表位只能有一个终端",
      type: "warning",
    });
    terminalParamVisible.value = false;
  } else {
    if (parm.terId != undefined && parm.terId) {
      msg = "修改";
      await terminalUpdate(parm)
        .then((res) => {
          init();
          ElMessage({
            message: msg + "成功",
            type: "success",
          });
          console.log(res);
          terminalParamVisible.value = false;
        })
        .catch((err) => {
          console.log(err);
          ElMessage({
            message: msg + "失败",
            type: "warning",
          });
          terminalParamVisible.value = false;
        });
    } else {
      await terminalSave(parm)
        .then((res) => {
          init();
          ElMessage({
            message: msg + "成功",
            type: "success",
          });
          // console.log(res);
          terminalParamVisible.value = false;
        })
        .catch((err) => {
          console.log(err);
          ElMessage({
            message: msg + "失败",
            type: "warning",
          });
          terminalParamVisible.value = false;
        });
    }
  }
};
//修改
const edit = () => {
  type.value = "2";
  if (currentData.value) {
    position.value = currentData.value.position + "";
    terminalParamVisible.value = true;
  } else {
    ElMessage({
      message: "请选择数据",
      type: "warning",
    });
  }
};
const isShow = () => {
  terminalParamVisible.value = false;
};
const rowClick = (row) => {
  // console.log(row);
  currentData.value = row;
};
const cellClick = (row, column) => {
  // console.log("cellClick", row, column.property);
  switch (column.property) {
    case "ip":
      row.ipState = !row.ipState;
      break;
    case "port":
      row.portState = !row.portState;
      break;
    default:
      break;
  }
};
const focusEvent = (row, index, column) => {
  if (column.property === "ip") {
    row.oldIp = row.ip;
  }
  if (column.property === "port") {
    row.oldPort = row.port;
  }
};
const blurEvent = (row, index, column) => {
  switch (column.property) {
    case "ip":
      row.ipState = !row.ipState;
      if (row.oldIp !== row.ip) {
        updateDevList(row);
      }
      break;
    case "port":
      row.portState = !row.portState;
      if (row.port !== row.oldPort) {
        updateDevList(row);
      }
      break;
    default:
      break;
  }

  // console.log("row", row);
};
const updateDevList = async (row) => {
  await devUpdate(row)
    .then((res) => {
      ElMessage({
        message: "编辑成功",
        type: "success",
      });
    })
    .catch((err) => {
      ElMessage({
        message: "编辑失败",
        type: "warning",
      });
    });
};
const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid) => {
    if (valid) {
      let parm = {
        newPassword: ruleForm.pass,
        oldPassword: ruleForm.oldPass,
      };
      let res = await userUpdatePassword(parm);
      if (res.code) {
        ElMessage({
          type: "warning",
          message: "修改失败",
        });
      } else {
        ruleForm.pass = "";
        ruleForm.oldPass = "";
        ElMessage({
          message: "修改成功",
          type: "success",
        });
      }
    } else {
      return false;
    }
  });
};
//重置
const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
};
//判断密码是否正确
const checkPwd = async () => {};
const setPwdStatue = async () => {
  try {
    let parm = {
      state: ruleForm.state ? 1 : 0,
    };
    let res = await userUpdateState(parm);
    if (res.code) {
      ElMessage({
        type: "warning",
        message: "修改失败",
      });
    } else {
      ElMessage({
        message: "修改成功",
        type: "success",
      });
    }
  } catch (error) {
    ElMessage({
      message: "修改失败",
      type: "warning",
    });
  }
};
const isPassword = async () => {
  try {
    let res = await userSelectState();
    if (res.data === "1") {
      ruleForm.state = true;
    } else {
      ruleForm.state = false;
    }
  } catch (error) {
    console.log(error);
  }
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
.system-container {
  width: 80%;
  margin: 0 auto;
  margin-top: 20px;
  .terminalParam-btn {
    display: flex;
    justify-content: end;
    margin-top: 10px;
  }
}
.device-settings {
  display: flex;
  justify-content: center;
  .device-settings-item {
    margin-right: 10px;
  }
}
.device-info {
  text-align: left;
  margin: 10px auto;
  width: 620px;
  border: 1px solid;
  padding: 10px;
  height: 300px;
  p {
    margin-bottom: 15px;
    .label {
      width: 120px;
      display: inline-block;
    }
  }
  .el-button {
    width: 100px;
  }
}
</style>
